/**
 * 表单方案按钮方法
 */
import FormSolutionApi from "@/common/api/form/formSolution.js";
import BpmInstApi from "@/common/api/bpm/bpmInst.js";
import { Util,MessageBox } from "@lowcode/jpaas-base-lib";
import {BpmImageView} from '@lowcode/jpaas-share-component';
import BpmInstStartConfirm from "@/views/modules/bpm/components/BpmInstStartConfirm.vue";

export default {
    methods: {
        /**
         * 提交按钮
         * @param {Object}  btn 按钮对象。
         * @returns {Promise<void>}
         */
        async submit(btn) {
            console.log('ButtonFunc.js')
            btn.loading = true;
            let action="save";
            let validRequired = this.canStartFlow ? false : true;
            let formBuild=this.getFormVm();
            let validResult= {success:true,msg:""};

            try{
                validResult= await formBuild.valid(validRequired,action)
            }
            catch (e){
                validResult= e;
            }
            if (validResult && !validResult.success ) {
                btn.loading = false;
                this.$message.warning((validResult && validResult.msg));
                return;
            }
            this.doSubmit(action, btn)
        },

        /**
         * 提交保存表单
         * @param {String}  action  动作
         * @param {Object}  btn     按钮对象。
         * @returns {Promise<void>}
         */
        async doSubmit(action, btn) {
            let formBuild=this.getFormVm();
            let data=formBuild.getData();
            //清除字段前后空格；
            Util.removeSpaces(data);
            if (this.parent && this.parent.field) {
                data[this.parent.field] = this.parent.value;
            }
            let self_=this;
            let json = {setting: {action: action, alias: this.formSolutionAlias}, data: data};
            FormSolutionApi.saveForm(json,this.appId).then(async res => {
                if (formBuild._afterSubmit) {
                    //如果_afterSubmit有返回结果并且rtn为success则返回。
                    let rtn= await formBuild._afterSubmit(res, json,action);
                    if(rtn && !rtn.success){
                        btn.loading = false;
                        return;
                    }
                }
                if (res.success) {
                    MessageBox[res.status]({title:this.$ti18('rxMsa.tipsInfo','提示信息'),msg:res.message});
                    if(res.status=="success"){
                        this.handSuccess(action,res,json,btn);
                    }
                    else{
                        btn.loading = false;
                    }
                }
                else{
                    //后端报错提示时前端就别提示了
                    if(!res.show){
                        if(MessageBox[res.status]){
                            MessageBox[res.status]({title:this.$ti18('rxMsa.tipsInfo','提示信息'),msg:res.message})
                        }else {
                            MessageBox.error({title:this.$ti18('rxMsa.tipsInfo','提示信息'),msg:res.message})
                        }
                    }
                    btn.loading = false;
                }
            })
        },
        /**
         * 数据保存成功的处理。
         * 1.当action为数据保存的时候
         *   1.保存刷新页面。
         * 2.当启动流程的时候
         *   1.当打开窗口的时候，则关闭窗口。
         *   2.当不是打开窗口时，则跳转到流程实例页面。
         * @param action
         * @param res
         */
        handSuccess(action,res,json,btn){
            if(action=="save" || action=="newSave" || action=="staging"){
                //如果外部指定了需要关闭，并且是弹窗模式则关闭窗口。
                if(this.closeOnSave && this.isOpenWindow){
                    let  result = {formJson: json, result: res.data};
                    this.closeWindow(result);
                }
                else{
                    //刷新页面。
                    this.formPkId=res.data.pk;
                    this.readonly=true;
                    if(btn){
                        btn.loading=false;
                    }
                    //树型表单
                    if(this.isTreeForm){
                        this.initTree();
                        return;
                    }
                    //重新初始化。
                    this.init();
                }
            }
            //启动流程。
            else{
                //弹窗。
                if(this.isOpenWindow){
                    var result = {formJson: json, result: res.data};
                    this.closeWindow(result);
                }
                else{
                    let name= this.$route.name;
                    let instId=res.data.instId;
                    //新窗口打开 则刷新
                    if("customform"==name || "customformNoPk"==name ){
                        if(btn){
                            btn.loading=false;
                        }
                        this.openInst(res.data.appId,instId);
                    }else {
                        //在页签启动流程
                        //刷新页面。
                        this.formPkId=res.data.pk;
                        this.readonly=true;
                        //重新初始化。
                        this.init();
                        //停止loading
                        if(btn){
                            btn.loading=false;
                        }
                    }
                }
            }
        },
        //流程图查看
        async flowImage(btn){
            if(!this.localDefId && !this.flowInstId){
                return;
            }
            let formBuild=this.getFormVm();
            let data=formBuild.getData();
            //清除字段前后空格；
            Util.removeSpaces(data);
            let conf={
                formData:data
            }
            if(this.localDefId){
                conf.defId=this.localDefId;
            }
            if(this.flowInstId){
                conf.instId=this.flowInstId;
            }
            Util.open({
                component:BpmImageView,
                curVm:this,
                widthHeight:['1024px','600px'],
                title:this.i18n('defaultBtns.flowImage','流程图'),
                data:conf
            },function (action){
            });
        },
        async startFlow(btn) {
            btn.loading = true;
            let action="start";
            var self_ = this;
            let formBuild=self_.getFormVm();
            let formData=formBuild.getData();
            //清除字段前后空格；
            Util.removeSpaces(formData);
            var params = {
                flowDefMapping: self_.formSolution.flowDefMapping,
                formJson: formData
            }
            var flowDefRes = await FormSolutionApi.getFlowDefId(params);
            var flowDefId = flowDefRes.data;
            if(!flowDefId){
                btn.loading = false;
                this.$message.warning(self_.i18n('msg.startFlowTips','无满足条件的流程定义！'));
                return;
            }
            var processConfigRes = await BpmInstApi.getProcessConfig(flowDefId);
            if (!processConfigRes.success) {
                btn.loading = false;
                this.$message.warning(processConfigRes.message);
                return;
            }
            if (processConfigRes.data) {
                var config = Util.deepClone(self_.processConfig);
                self_.processConfig = Object.assign(config, processConfigRes.data);
                self_.handleProcessConfig(self_.processConfig);
            }
            //对表单数据进行校验
            let validResult= {success:true,msg:""};
            try{
                validResult= await formBuild.valid(true,action)
            }
            catch (e){
                validResult= e;
            }
            if (!validResult.success) {
                btn.loading=false;
                this.$message.warning(validResult.msg);
                return;
            }
            if (self_.processConfig.startConfirm && !self_.needConfirmDlg) { //启动流程确认
                self_.$confirm({
                    title: self_.$ti18('rxMsa.tipsInfo','提示信息'),
                    content: self_.i18n('msg.confirmStartFlow','确认提交审批吗？'),
                    okText: self_.$ti18('rxForm.ackBtn','确认'),
                    cancelText: self_.$ti18('rxForm.cancelBtn','取消'),
                    zIndex: 20000,
                    onOk() {
                        self_.doSubmit(action,btn);
                    },
                    onCancel() {
                        btn.loading = false;
                    },
                });
            } else if (self_.needConfirmDlg) { //是否确认
                let formJson = {};
                let alias = this.formAlias?this.formAlias:this.formSolution.formName
                formJson[alias]=formData;
                let conf = {
                    curVm: self_,
                    title: self_.i18n('list.startFlowTitle','流程启动确认'),
                    component: BpmInstStartConfirm,
                    data: {
                        formSolutionAlias: self_.formSolutionAlias,
                        processConfig: self_.processConfig,
                        defId: flowDefId,
                        formData:formJson,
                        instId: self_.flowInstId  || formData.instId || formData.INST_ID_
                    },
                    widthHeight: ['800px', '520px']
                };
                btn.loading = false;
                Util.open(conf, async function (action, data) {
                    if (action != 'ok') return;

                    if (formBuild._afterSubmit) {
                        //如果_afterSubmit有返回结果并且rtn为success则返回。
                        //let rtnObj={data:result.data,result:data};
                        let rtn= await formBuild._afterSubmit(data.result,data.data, action);
                        if(rtn && !rtn.success){
                            btn.loading = false;
                            return;
                        }
                    }

                    self_.handSuccess(action,data,formData,btn)
                });
            } else {
                self_.doSubmit(action,btn);
            }
        },
        handleProcessConfig(newVal) {
            let fillOpinion = false;
            let assignFlowUsers = false;
            let startCalFlowusers = false;
            //允许选择路径
            let allowSelectPath = newVal.allowSelectPath;
            let assignBatchFlowUsers=newVal.assignBatchFlowUsers;
            var startOptions = newVal.startNodeOptions;

            if (startOptions instanceof Array) {
                this.processConfig.startConfirm = startOptions.indexOf('startConfirm') != -1;
                fillOpinion = startOptions.indexOf('fillOpinion') != -1;
                assignFlowUsers = startOptions.indexOf('assignFlowUsers') != -1;
                startCalFlowusers = startOptions.indexOf('startCalFlowusers') != -1;
            }
            if (assignBatchFlowUsers || fillOpinion || assignFlowUsers || startCalFlowusers || allowSelectPath) {//需要显示弹出对话框
                this.needConfirmDlg = true;
            }
        },
        closeWindow(json) {
            // 保存数据成功并关闭页面发出saveSuccess事件
            this.$bus.emit("saveSuccess", {formJson:json.formJson,key:this.layerid})
            //this.$emit("saveSuccess",json);
            Util.closeWindow(this, 'ok', json);
        },
        /**
         * 复制添加
         * @param btn
         * @returns {Promise<void>}
         */
        async newSubmit(btn){
            let action="newSave";
            var validRequired = this.canStartFlow ? false : true;
            let formBuild=this.getFormVm();
            let validResult= {success:true,msg:""};
            try{
                validResult= await formBuild.valid(validRequired,action)
            }
            catch (e){
                validResult= e;
            }
            if (!validResult.success) {
                btn.loading=false;
                this.$message.warning(validResult.msg);
                return;
            }
            this.doSubmit(action, btn)
        },
        /**
         *暂存
         * @param btn
         * @returns {Promise<void>}
         */
        async staging(btn) {
            btn.loading=true;
            let action="staging";
            let formBuild=this.getFormVm();
            let validResult= {success:true,msg:""};
            try{
                validResult= await formBuild.valid(false,action)
            }
            catch (e){
                validResult= e;
            }
            if (!validResult.success) {
                btn.loading=false;
                this.$message.warning(validResult.msg);
                return;
            }
            this.doSubmit(action, btn)
        },
        /**
         * 编辑
         */
        edit(){
            this.readonly=false;
            //重新初始化。
            this.init();
        },
        /**
         * 提交并继续
         */
        submitAndContinue(btn){
            btn.loading=true;
            let formBuild=this.getFormVm();
            let data=formBuild.data;
            //清除字段前后空格；
            Util.removeSpaces(data);
            if (this.parent && this.parent.field) {
                data[this.parent.field] = this.parent.value;
            }
            let self_=this;
            let action = "save"
            let json = {setting: {action: action, alias: this.formSolutionAlias}, data: data};
            FormSolutionApi.saveForm(json).then(async res => {
                if (formBuild._afterSubmit) {
                    //如果_afterSubmit有返回结果并且rtn为success则返回。
                    let rtn= await formBuild._afterSubmit(res, json,action);
                    if(rtn && !rtn.success){
                        btn.loading = false;
                        return;
                    }
                }
                btn.loading = false;
                MessageBox[res.status]({title:this.$ti18('rxMsa.tipsInfo','提示信息'),msg:res.message});

                if(res.status=="success"){
                    //刷新页面。
                    self_.formPkId="";
                    self_.readonly=false;
                    //树型表单
                    if(self_.isTreeForm){
                        self_.initTree();
                        return;
                    }
                    //重新初始化。
                    self_.init();
                }
            })
        }
    }
}
